#include "ParamReferLimitsView.h"
#include "ui_ParamReferLimitsForm.h"
#include <QPainter>
#include <QSqlRecord>
#include <QSqlQuery>
#include <QDebug>
#include "GlobalApi/sqlitedb.h"
#include "Auxiliary/View/MessageBoxDialog.h"

ParamReferLimitsView::ParamReferLimitsView(QWidget *parent) : QWidget(parent),
  ui(new Ui::ParamReferLimits)
{
    ui->setupUi(this);
    tc = QTextCodec::codecForName("UTF-8");
    initUi();
}

ParamReferLimitsView::~ParamReferLimitsView()
{
   delete ui;
}

void ParamReferLimitsView::closeEvent(QCloseEvent *event)
{

}

void ParamReferLimitsView::initUi()
{
    initModel();
    initTable();
    m_SelectRow = 1;
    ui->tableWidget_limits->selectRow(0);
    connect(ui->tableWidget_limits, SIGNAL(cellPressed(int,int)),this,SLOT(resultSelect(int,int)));
}

void ParamReferLimitsView::initModel()
{
    // 关联数据库表模型
    pModel = new QSqlTableModel(this, SqliteDb::getInstance()->getDB());
    pModel->setTable("ParamGroupLimitsTable");
    pModel->select();
    pModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
}

void ParamReferLimitsView::initTable()
{
    int recordRow = pModel->rowCount();
    int rowNum = recordRow+1;  //由于通用参考组占用2行，所以创建时需要多一行
    ui->tableWidget_limits->setRowCount(rowNum);
    ui->tableWidget_limits->setColumnCount(6);


    ui->tableWidget_limits->verticalHeader()->setResizeMode(QHeaderView::Stretch);
    ui->tableWidget_limits->verticalHeader()->setDefaultAlignment(Qt::AlignCenter);
    ui->tableWidget_limits->horizontalHeader()->setClickable(false); //设置表头不可点击（默认点击后进行排序）

    //设置表头内容
    QStringList header;
    header<<tr("")<<tr("参考组名称")<<tr("默认参考组")<<tr("年龄下限(>)")<<tr("年龄上限(<=)")<<tr("性别");
    ui->tableWidget_limits->setHorizontalHeaderLabels(header);

    //设置表头字体加粗
    ui->tableWidget_limits->horizontalHeader()->setStretchLastSection(true); //设置充满表宽度
    ui->tableWidget_limits->verticalHeader()->setResizeMode( QHeaderView::Fixed );
    //ui->tableWidget_limits->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
    ui->tableWidget_limits->setFrameShape(QFrame::NoFrame); //设置无边框
    ui->tableWidget_limits->setShowGrid(false); //设置不显示格子线
    ui->tableWidget_limits->setEditTriggers(QAbstractItemView::NoEditTriggers);//编辑
    ui->tableWidget_limits->horizontalHeader()->setFixedHeight(33); //设置表头的高度
    ui->tableWidget_limits->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget_limits->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget_limits->horizontalHeader()->setStyleSheet("QHeaderView::section{background:rgb(102, 204, 153);gridline-color: rgb(255, 255, 255);border:1px solid#c9c9c9;}"); //设置表头背景色

    ui->tableWidget_limits->verticalHeader()->hide();
    //ui->tableWidget_limits->horizontalHeader()->hide();

    // 设置列宽
    ui->tableWidget_limits->setColumnWidth(0,38);
    for( int i=1; i<6; ++i )
    {
        ui->tableWidget_limits->setColumnWidth(i, 132);
    }

    QString stylesheettableWidget_listing = "QTableWidget{background-color:#e2f7eb;"
                                            "alternate-background-color: #ffffff;"
                                            "color: rgb(0, 0, 0);"
                                            "border:1px solid#C9C9C9;"
                                            "selection-color: rgb(255, 255, 255);"
                                            "selection-background-color: rgb(32, 131, 95);}";

    ui->tableWidget_limits->setAlternatingRowColors(true);//间隔显示颜色
    ui->tableWidget_limits->setStyleSheet(stylesheettableWidget_listing);

    for(int i = 0; i < rowNum; ++i)
    {
        QTableWidgetItem *item = new QTableWidgetItem();
        item->setText(QString::number(i+1, 10) );
        item->setTextAlignment(Qt::AlignCenter);
        item->setFlags(item->flags()&~Qt::ItemIsSelectable);
        ui->tableWidget_limits->setItem(i, 0, item);
        ui->tableWidget_limits->item(i,0)->setTextColor( QColor(0, 0, 0) );
        ui->tableWidget_limits->item(i,0)->setBackgroundColor(QColor(102, 204, 153));
        ui->tableWidget_limits->setRowHeight(i, 35);
        ui->tableWidget_limits->setShowGrid(true);

    }


    for(int i = 0; i < rowNum; i++)
    {
        if(i >= 1)
        {
            QSqlRecord record = pModel->record(i-1);
            QString strGroupName, strAgeLow, strAgeHigh, strSex;
            strGroupName = record.value("paramGroupName").toString();
            strAgeLow = record.value("ageLowerLimit").toString();
            strAgeHigh = record.value("ageUpperLimit").toString();
            strSex = record.value("sex").toString();

            QByteArray ba1 = tc->fromUnicode( strGroupName );
            char *name = ba1.data();
            QByteArray ba2 = tc->fromUnicode( strAgeLow );
            char *ageDown = ba2.data();
            QByteArray ba3 = tc->fromUnicode( strAgeHigh );
            char *ageUp= ba3.data();
            QByteArray ba4 = tc->fromUnicode( strSex );
            char *sex = ba4.data();

            if(i == 1)
            {
                ui->tableWidget_limits->setItem(0,1, new QTableWidgetItem(""));
                ui->tableWidget_limits->setItem(0,2, new QTableWidgetItem(""));
                ui->tableWidget_limits->setItem(0,3, new QTableWidgetItem(""));
                ui->tableWidget_limits->setItem(0,4, new QTableWidgetItem(""));
                ui->tableWidget_limits->setItem(0,5, new QTableWidgetItem(sex));


                ui->tableWidget_limits->setItem(i,1,new QTableWidgetItem(name));
                ui->tableWidget_limits->setItem(i,2,new QTableWidgetItem(""));
                ui->tableWidget_limits->setItem(i,3,new QTableWidgetItem(ageDown));
                ui->tableWidget_limits->setItem(i,4,new QTableWidgetItem(ageUp));
                ui->tableWidget_limits->setItem(i,5,new QTableWidgetItem(""));
            }
            else
            {
                ui->tableWidget_limits->setItem(i,1,new QTableWidgetItem(name));
                ui->tableWidget_limits->setItem(i,2,new QTableWidgetItem(""));
                ui->tableWidget_limits->setItem(i,3,new QTableWidgetItem(ageDown));
                ui->tableWidget_limits->setItem(i,4,new QTableWidgetItem(ageUp));
                ui->tableWidget_limits->setItem(i,5,new QTableWidgetItem(sex));
            }
        }

    }

    ui->tableWidget_limits->setSpan(0, 1, 2, 1);
    ui->tableWidget_limits->setSpan(0, 2, 2, 1);    //第一行和第二行的部分单元格合并


    for(int i = 0; i < rowNum; i++)
    {
        for(int j = 0; j < 6; j++)
        {
            ui->tableWidget_limits->item(i, j)->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget_limits->item(i, j)->setTextColor( QColor(0, 0, 0) );
        }

    }
}

void ParamReferLimitsView::on_Btn_new_clicked()
{
  int rowNum =  ui->tableWidget_limits->rowCount();
  if(rowNum  <= 11)
  {
      paramGroupLimitsView = new ParamGroupLimitsView(true, -1, pModel,  this);
      connect(paramGroupLimitsView, SIGNAL(updateParamReferView(int)), this, SLOT(updateTableView(int)));
      paramGroupLimitsView->show();
  }
  else
  {
      MessageBoxDialog *messageBox = new MessageBoxDialog(NULL, QString(tr("自定义参考组已满5个！")));
      messageBox->exec();
      return;
  }
}

void ParamReferLimitsView::on_Btn_edit_clicked()
{
    int selectGroup = m_SelectRow-1;
    paramGroupLimitsView = new ParamGroupLimitsView(false, selectGroup, pModel, this);
    connect(paramGroupLimitsView, SIGNAL(updateParamReferView(int)), this, SLOT(updateTableView(int)));
    paramGroupLimitsView->show();

}

void ParamReferLimitsView::on_Btn_del_clicked()
{
    if(m_SelectRow <= 5) // 固定组不可删除
    {
       MessageBoxDialog *messageBox = new MessageBoxDialog(NULL, QString(tr("固定参考组不允许删除。")));
       messageBox->exec();
       return;
    }
    else if(m_SelectRow > 5)
    {
        MessageBoxDialog *messageBox = new MessageBoxDialog(NULL, QString(tr("是否确认删除？")));
        int result = messageBox->exec();
        if(result == QDialog::Accepted)
        {
            int recordRow = m_SelectRow-1;
            pModel->removeRow(recordRow);
            pModel->database().transaction();
            if(pModel->submitAll()){
               pModel->database().commit();
            } else {
               pModel->database().rollback();
            }
            updateTableView(m_SelectRow);

        } else {

        }
        messageBox->deleteLater();
    }
}

void ParamReferLimitsView::on_Btn_default_clicked()
{

}

void ParamReferLimitsView::resultSelect(int row, int column)
{
    if( row == 0 || row == 1 )
    {
        m_SelectRow = 1;
        ui->tableWidget_limits->selectRow(0);
    }
    else
    {
        m_SelectRow = row;  //当前选中行
    }

    qDebug()<<"Select Row"<<m_SelectRow;

}

void ParamReferLimitsView::updateTableView(int selectRow)
{
    initTable();
    int rowCount = pModel->rowCount();

    if(selectRow == 0 || selectRow == 1)
    {
       ui->tableWidget_limits->selectRow(0);
    }
    else if(selectRow <= rowCount)
    {
        ui->tableWidget_limits->selectRow(selectRow);
    }
    else
    {
        ui->tableWidget_limits->selectRow(rowCount);
    }
}

